import { FileModel } from '@/services/model/fileModel';
import config from './config';
import { isEmpty, isNull } from './is';
import { HideLoading, Loading, Toast } from './uniapi/prompt';
import { useAuthStore } from '@/store/modules/auth';
import { ResultEnum } from '@/enums/httpEnum';

/**
 * 上传图片
 * @param file 文件对象
 */
export function uploadImage(file: FileModel, callback?: Function) {
  if (isNull(file)) {
    Toast('文件为空');
    return;
  }
  const authStore = useAuthStore();

  Loading('上传中');
  uni.uploadFile({
    url: config.url.upload_image,
    header: {
      authorization: `Bearer ${authStore.getToken}`,
    },
    formData: {},
    filePath: file.url,
    name: 'file',
    success: (uploadFileRes) => {
      HideLoading();
      if (uploadFileRes.statusCode == ResultEnum.SUCCESS) {
        if (typeof callback === 'function') {
          // 数据加载完成回调函数
          callback(uploadFileRes.data);
        }
      }
    },
    fail: () => {
      Toast('上传失败！');
    },
    complete: function () {
      HideLoading();
    },
  });
}

/**
 * 批量上传图片
 * @param files 文件对象
 */
export function uploadImages(files: Array<UniApp.UploadFileOptionFiles>, callback?: Function) {
  if (isEmpty(files)) {
    Toast('文件为空');
    return;
  }

  const authStore = useAuthStore();

  Loading('上传中');

  uni.uploadFile({
    url: config.url.upload_images,
    header: {
      authorization: `Bearer ${authStore.getToken}`,
    },
    formData: {},
    files: files,
    success: (uploadFileRes) => {
      HideLoading();
      if (uploadFileRes.statusCode == ResultEnum.SUCCESS) {
        if (typeof callback === 'function') {
          // 数据加载完成回调函数
          callback(uploadFileRes.data);
        }
      }
    },
    fail: () => {
      Toast('上传失败！');
    },
    complete: function () {
      HideLoading();
    },
  });
}
